/*
 * @Autor: Shihh
 * @Description: 
 * @Version: 1.0
 * @Date: 2020-05-10 15:20:07
 */

const Sequelize = require('sequelize')
const Op = Sequelize.Op;
var comm = require('../comm')

module.exports = (sequelize, DataTypes) => {

    class m_category extends Sequelize.Model {
        /**
         * @author: xgq
         * @description: 
         * @param {type} 
         * @return: 
         */
        static async getCategoryByNameOrById(param) {
            let querydata = []
            querydata = await this.findAll({
                where: {
                    // [Op.or]: [{ id: param }, { name: { [Op.like]: `%${param}%` } }]
                    [Op.or]: [{ code: { [Op.like]: `%${param}%` } }, { name: { [Op.like]: `%${param}%` } }]

                }
            })
            return querydata;
        }

        static async setAllInRedis() {
            let condition = {
                raw: true,
            }
            let querydata = await this.findAll(condition)
            for (let item of querydata) {
                comm.redis.hset('category', item.id, JSON.stringify(item), function (err, data) {
                })
            }
        }

        /**
         * @author: Shihh
         * @description: 条件查询分类
         * @param {type} 
         * @return: 
         */
        static async getCategoryListByAdmin(pars) {
            var querydata = []
            let condition = {
                attributes: ['id', 'name', 'code', 'en_name','thumbnail', 'parentid', 'remark'],
                raw: true
            }
            if (pars !== undefined) {
                condition = Object.assign(condition, pars, condition)
            }
            querydata = await this.findAll(condition)
            return { "rows": querydata };
        }
        /**
          * @author: xgq
          * @description: 
          * @param {type} 
          * @return: 
          */
        static async getCategoryNameById(id) {
            var querydata = []
            let condition = {
                attributes: ['name'],
                raw: true,
                where: { id }
            }
            querydata = await this.findOne(condition)
            return querydata;
        }

        static async getCategoryByName(name){
            let Ids=await this.findAll({where:{name: { [Op.like]: '%' + name + '%'}},raw:true})
            return Ids
        }
    }

    m_category.init({
        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
        name: { type: DataTypes.STRING(64) },
        code: { type: DataTypes.STRING(64) },
        en_name: { type: DataTypes.STRING(64) },
        thumbnail: { type: DataTypes.STRING(255) },
        parentid: { type: DataTypes.INTEGER },
        remark: { type: DataTypes.STRING(255) },
        zindex: { type: DataTypes.INTEGER },
    }, {
        sequelize,
        modelName: 'category',
        freezeTableName: true,
        timestamps: false
    });

    return m_category;
}

